"""
需求：请求IHRM项目的登录接口
url: http://ihrm-test.itheima.net/api/sys/login
请求方式：POST
请求体-json提交：
    登陆成功：mobile: 13800000002, password: 123456
    用户不存在：mobile: 13800002332, password: 123456
    密码错误：mobile: 13800000002, password: 123abc
"""

# 1. 导入unittest包和HTMLTestReport工具
import unittest
import requests
from htmltestreport import HTMLTestReport


# 2. 自定义测试类
# 注意: 必须继承自 unittest.TestCase
class TestLogin(unittest.TestCase):
    """测试类"""

    # 3. 自定义测试方法
    # 注意: 必须以 test 开头(字母必须全小写, 别拼错单词, 例如: text)
    # 登录成功
    def test01_login_success(self):
        # 测试数据
        mobile = "13800000002"
        password = "123456"
        login_info = {
            "mobile": mobile,
            "password": password
        }

        # 发送请求
        url = "http://ihrm-test.itheima.net/api/sys/login"
        response = requests.post(url, json=login_info)
        print("json data =", response.json())

        # 断言
        json_data = response.json()
        self.assertEqual(200, response.status_code)
        self.assertEqual(True, json_data.get("success"))
        self.assertEqual(10000, json_data.get("code"))
        self.assertIn("操作成功", json_data.get("message"))

    def test01_login_user_err(self):
        # 测试数据
        mobile = "13800001232"
        password = "123456"
        login_info = {
            "mobile": mobile,
            "password": password
        }

        # 发送请求
        url = "http://ihrm-test.itheima.net/api/sys/login"
        response = requests.post(url, json=login_info)
        print("json data =", response.json())

        # 断言
        json_data = response.json()
        self.assertEqual(200, response.status_code)
        self.assertEqual(False, json_data.get("success"))
        self.assertEqual(20001, json_data.get("code"))
        self.assertIn("用户名或密码错误", json_data.get("message"))

    def test01_login_pwd_err(self):
        # 测试数据
        mobile = "13800000002"
        password = "123abc"
        login_info = {
            "mobile": mobile,
            "password": password
        }

        # 发送请求
        url = "http://ihrm-test.itheima.net/api/sys/login"
        response = requests.post(url, json=login_info)
        print("json data =", response.json())

        # 断言
        json_data = response.json()
        self.assertEqual(200, response.status_code)
        self.assertEqual(False, json_data.get("success"))
        self.assertEqual(20001, json_data.get("code"))
        self.assertIn("用户名或密码错误", json_data.get("message"))


if __name__ == '__main__':
    # - 如果测试用例，和生成测试报告在同一个文件
    # - 需要通过命令运行代码，才能生成测试报告
    # 2. 生成测试套件
    suite = unittest.defaultTestLoader.discover('./', 'hm11*')

    # 3. 实例化HTMLTestReport对象
    report = HTMLTestReport('./report.html', title="测试报告", description="V1.0")

    # 4. 执行测试套件
    report.run(suite)
